package griffin.website;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import android.widget.Toast;

//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.ksoap2.SoapEnvelope;
//import org.ksoap2.serialization.SoapObject;
//import org.ksoap2.serialization.SoapSerializationEnvelope;
//import org.ksoap2.transport.HttpTransportSE;



import CIT.Test.GalleryFlow;
import CIT.Test.ImageAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
//import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
//import android.widget.Toast;
import android.widget.ImageButton;
//import android.widget.Button;
//import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
//import java.util.concurrent.atomic.AtomicBoolean;

import griffin.logic.userLogic;

public class home extends Activity {
	private static final String TAG = "[home]";
//    private static final String SOAP_ACTION = "http://tempuri.org/getBookmarks";
//    private static final String METHOD_NAME = "getBookmarks";
//    private static final String NAMESPACE = "http://tempuri.org/";
//    private static final String URL = "http://griffin.ciandt.cn/Sservice1.asmx";
//	private static final int BOOKMARKNUMS = 6;			//Homepage's number of bookmarks.
	private String loginusername = "";
//	private int loginuserid = 0;
	private ImageButton btnLoginOut;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private Integer[] images={R.drawable.bookmarksilver, R.drawable.filesystemfolderopen,
			R.drawable.miscellaneous,R.drawable.packagesettings};
	private String[] imagesTitle = {"Living","Leisure","Tools","Region"}; 
	userLogic userlogic = new userLogic(this);
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d(TAG, "[onCreate...] ");	
        super.onCreate(savedInstanceState);
        prepareCategoryData();
        
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Log.d(TAG,"[onConfigurationChanged:====LANDSCAPE");
			setContentView(R.layout.coverflow);
			
			//logic
			coverflow();	
		}else{
			Log.d(TAG,"[onConfigurationChanged:====PORTRAIT");			
	        setTitle("Home");
	        setContentView(R.layout.main);
	        
			getLoginInfo();
	        
	        getBookmarks();
	        
			getCategories();
			
			setWelcomeInfo();
		}
    }
    
    private void coverflow(){
        ImageAdapter adapter = new ImageAdapter(this, images);
        adapter.createReflectedImages();

        GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
        galleryFlow.setAdapter(adapter);
        
        galleryFlow.setCallbackDuringFling(true);
        galleryFlow.setOnItemClickListener(new GalleryFlow.OnItemClickListener(){
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
	        	Log.d(TAG,"[Position :( "+ position+")");	        	
	        	gotoSubCategory(position);
            }
        });
        galleryFlow.setOnItemSelectedListener(new GalleryFlow.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            	Toast.makeText(home.this, imagesTitle[position],Toast.LENGTH_SHORT).show();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            	int i=0;
            	i++;
            }
        });
    }
    
    private void setWelcomeInfo()
    {
    	TextView tv = (TextView)findViewById(R.id.txtWelcome);
    	if (loginusername != "")
    	{
    		tv.setText("Hello " + loginusername + "!");
    	}
    	else
    	{
    		tv.setText("Hello guest,Please login!");
    	}
    }

	private void getBookmarks() {
//		if(loginuserid>0){
//			ListView bookmarksite = (ListView)findViewById(R.id.lvBookmarkedSite);
//			SimpleAdapter adapter = new SimpleAdapter(this,
//						getBookmarkData(loginuserid),
//                         R.layout.homebookmarklist,
//                         new String[] {"ItemText"},
//                         new int[] {R.id.homebookmarktitle});
//			bookmarksite.setAdapter(adapter);
//			bookmarksite.setOnItemClickListener(new ItemClickListener());
//		}
	}

	private void getLoginInfo() {
		btnLoginOut = (ImageButton)findViewById(R.id.btnLoginOut);
		AtomicReference<String> strUsername=new AtomicReference<String>("");
    	AtomicReference<String> strPassword=new AtomicReference<String>("");
    	AtomicInteger userid=new AtomicInteger(0);
		if(userlogic.getLoginUser(strUsername, strPassword, userid)){
			//show loginOut
			btnLoginOut.setVisibility(View.VISIBLE);
			loginusername = strUsername.get();
//			loginuserid = userid.get();
			
			Log.d(TAG, "[Login with] "+loginusername);		
		}else{
			//hide loginOut
			btnLoginOut.setVisibility(View.INVISIBLE);
			
			Log.d(TAG, "[No Login] ");	
		}
		
		btnLoginOut.setOnClickListener(new OnClickListener(){
	 		public void onClick(View v){
	 			loginOut();
	 		}
	 	});
	}
	
	private void loginOut(){
		userlogic.loginOut();
    	
    	btnLoginOut = (ImageButton)findViewById(R.id.btnLoginOut);
    	btnLoginOut.setVisibility(View.INVISIBLE);
    	
    	Intent intentGo = new Intent();
    	intentGo.setClass(home.this,tabframework.class);
    	
    	Log.d(TAG, "[Login out] ");	
    	startActivity(intentGo);
	}
	
	private void getCategories() {
		SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.nightitem,
		new String[]{"ItemText","ItemImage"},
		new int[]{R.id.ItemText,R.id.ItemImage});
		GridView listView= (GridView)findViewById(R.id.lvCategory);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new WebSiteItemClickListener());
	}
	
	class  WebSiteItemClickListener implements OnItemClickListener     
	{     
		 public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened      
		                                   View arg1,//The view within the AdapterView that was clicked     
		                                   int arg2,//The position of the view in the adapter     
		                                   long arg3//The row id of the item that was clicked     
		                                   ) {       
			 gotoSubCategory(arg2);
		 }  
	}
	
	private void gotoSubCategory(int position){		
		 HashMap<String, Object> item=(HashMap<String, Object>) list.get(position);  
		 //show selected Item's ItemText  
		 DisplayToast((String)item.get("ItemText"));
		 
		 saveCurCategory((String)item.get("ItemID"), (String)item.get("ItemText"));
		 Log.d(TAG, "[Login out] ");	
		 
		 Intent intent = new Intent();
		 intent.setClass(home.this, list.class);
		 startActivity(intent);
	}
	
	private void saveCurCategory(String curCategoryID, String curCategoryName) {
		SharedPreferences loginInfo=getSharedPreferences("griffin.website.curcate", 0);
    	SharedPreferences.Editor editor=loginInfo.edit();
    	editor.putString("curcategoryid", curCategoryID); 	
    	editor.putString("curcategoryname", curCategoryName); 	
    	editor.commit();
	}
	
	class  ItemClickListener implements OnItemClickListener     
	{     
		 public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened      
		                                   View arg1,//The view within the AdapterView that was clicked     
		                                   int arg2,//The position of the view in the adapter     
		                                   long arg3//The row id of the item that was clicked     
		                                   ) {       
		     HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);    
		     DisplayToast((String)item.get("ItemText"));
		     openUrl(((String)item.get("ItemUrl")).trim());
		 }
	}
     
	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent); 
	}

 	public void DisplayToast(String str)
 	{
 		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 	}
	
	public static boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]+");
	    return pattern.matcher(str).matches();   
	 } 
	
	private void prepareCategoryData() {
//    	Integer[] images = { R.drawable.bookmarksilver, R.drawable.filesystemfolderopen,
//      R.drawable.img0100, R.drawable.img0130 };
//		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	    String databaseFilename = tabframework.DATABASE_PATH + "/" + tabframework.DATABASE_FILENAME;
	    SQLiteDatabase db;
	    
	    db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
	    Cursor result=db.rawQuery("SELECT VG_ID,VG_ENGLISH,VG_IMAGEURL FROM VG_TopCategories", null); 
	    if (result.moveToFirst())
	    {
	    	int index =0;
	        while (!result.isAfterLast()) { 
	        	String categoryid = result.getString(0);
	            String category =result.getString(1);
//	            String strimgurl = result.getString(2);
//	            int imgurl=Integer.parseInt(strimgurl);
	            int imgurl=images[index++];
	        	Map<String, Object> map = new HashMap<String, Object>();
	        	map.put("ItemID", categoryid);
	        	map.put("ItemText", category);
	        	map.put("ItemImage", imgurl);
	        	list.add(map);
	            result.moveToNext(); 
	          }
	    }
	    result.close(); 
	    db.close();
	}
	
//	private List<Map<String, Object>> getBookmarkData(int userid){
//		List<Map<String, Object>> bookmarkList = new ArrayList<Map<String, Object>>();
//		
//		if (userid != 0)
//		{
//			try{
//				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//		        request.addProperty("userid", userid);
//	
//		        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//		        envelope.dotNet=true;
//		        envelope.setOutputSoapObject(request);
//	
//		        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//		        androidHttpTransport.call(SOAP_ACTION, envelope);
//	
//		        Object result = (Object)envelope.getResponse();  
//		        try 
//		        {   
//		        	JSONObject jsonObj = new JSONObject(result.toString());
//		            JSONArray bookmarkArr = jsonObj.getJSONArray("bookmarks");
//		            
//		            for(int i = 0; i < bookmarkArr.length() && i < BOOKMARKNUMS; i++)
//		            {
//		            	Map<String, Object> map = new HashMap<String, Object>();
//		            	map.put("ItemUrl", bookmarkArr.getJSONObject(i).getString("Bookmarkurl"));
//		            	map.put("ItemText", bookmarkArr.getJSONObject(i).getString("Bookmarkname"));
//		            	bookmarkList.add(map);
//		            }
//		        } 
//		        catch (JSONException e) 
//		        {   
//		        	e.printStackTrace();   
//		        }    
//			}catch(Exception ex){
//				//TODO maybe need to throw
//				ex.printStackTrace(); 
//			}
//		}
//		
//		return bookmarkList;
//	}
    
    

    
}